<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-row>
          <el-col :span="22">
            <!-- 表单头部 -->
            <el-form
              ref="form"
              class="formfixe"
              :model="form"
              label-width="80px"
            >
              <el-form-item label="关键字" size="small">
                <el-input
                  v-model="form.keyword"
                  class="el-input__innerr"
                  placeholder="根据文章标题搜索"
                />
              </el-form-item>
              <el-form-item label="状态" size="small">
                <el-select
                  v-model="form.state"
                  placeholder="请选择"
                  class="el-input__innerr"
                >
                  <el-option
                    v-for="obj in stateObj"
                    :key="obj.id"
                    :label="obj.name"
                    :value="obj.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label-width="10px" class="formItem">
                <el-button size="small" @click="delFormValue">清除</el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="onSubmit"
                >搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <!-- 新增技巧 -->
          <el-col :span="2" style="text-align: right">
            <el-button type="success" size="small" @click="setArticleFn">
              <i class="el-icon-edit" />新增技巧</el-button>
          </el-col>
        </el-row>
        <!-- 数据总量 -->
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <i class="el-icon-info" /><span class="span-font">数据一共有{{ counts }}条</span>
            </div>
          </el-col>
        </el-row>
        <!-- 技巧表格 -->
        <el-table :data="tableData" style=" margin: 20px 0">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="title" label="文章标题" width="400">
            <template
              slot-scope="scope"
            >{{ scope.row.title }}
              <i
                v-if="scope.row.videoURL"
                class="el-icon-film"
                style="color: #0000ff"
                @click="videoFn(scope.row.videoURL)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="visits" label="阅读数" />
          <el-table-column prop="username" label="录入人" />
          <el-table-column prop="createTime" label="录入时间">
            <template slot-scope="scope">{{ scope.row.createTime | fromTime }}</template>
          </el-table-column>
          <el-table-column prop="state" label="状态" width="100">
            <template slot-scope="scope">{{
              stateFn(scope.row.state)
            }}</template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  @click="perciewArticle(scope.row)"
                >预览</el-button>
                <el-button
                  type="text"
                  @click="setStartFn(scope.row.state, scope.row.id)"
                >{{ scope.row.state === 1 ? "禁用" : "启用" }}</el-button>
                <el-button
                  type="text"
                  :disabled="scope.row.state === 1"
                  @click="editArticleFn(scope.row.id)"
                >修改</el-button>
                <el-button
                  type="text"
                  :disabled="scope.row.state === 1"
                  @click="removeArticleFn(scope.row)"
                >删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <el-pagination
          v-if="counts < query.pagesize ? false : true"
          background
          :current-page.sync="query.page"
          :page-size="query.pagesize"
          :page-sizes="[5, 10, 20, 50]"
          layout="prev, pager, next, sizes, jumper"
          :total="counts"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />

        <!-- 修改文章 新增文章组件 -->
        <el-dialog
          :title="isEdit?'修改文章':'新增文章'"
          :visible.sync="addDialogVisible"
          width="40%"
          @close="closeFn"
        >
          <articles
            v-if="addDialogVisible"
            ref="addArticle"
            :articleid="ArticleId"
            :is-edit="isEdit"
            @close="addClose"
            @closeCancel="closeCancel"
          />
        </el-dialog>

        <!-- 预览文章 组件 -->
        <el-dialog
          title="预览文章"
          :visible.sync="previewDialogVisible"
          width="42%"
        >
          <articles-preview
            v-if="previewDialogVisible"
            :articlesobj="ArticlesPreviewOBj"
          />
        </el-dialog>

        <!-- 视频组件 -->
        <el-dialog class="dialog-displacement" :visible.sync="videoDialogVisible" :close-on-click-modal="false">

          <video-player
            v-if="videoDialogVisible"
            ref="videoPlayer"
            :style="!videoState?'opacity: 0;':'opacity: 1;'"
            class="video-player vjs-custom-skin video-style"
            :playsinline="true"
            :options="playerOptions"
            @loadeddata="onPlayerLoadeddata($event)"
          />

          <div v-if="videoDialogVisible" class="close-video" @click="videoDelFn"><i class="el-icon-close i-font" /></div>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
import Articles from '@/module-hmmm/components/articles-add'
import ArticlesPreview from '@/module-hmmm/components/articles-preview'
import { list, changeState, remove } from '@/api/hmmm/articles'
import * as dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear' // import plugin
import 'dayjs/locale/zh-cn' // import locale

dayjs.extend(isLeapYear) // use plugin
dayjs.locale('zh-cn') // use locale
export default {
  components: {
    Articles,
    ArticlesPreview,
    videoPlayer
  },
  filters: {
    fromTime(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  data() {
    return {
      stateObj: [
        // 枚举数据
        {
          name: '禁用',
          id: 0
        },
        {
          name: '开启',
          id: 1
        }
      ],

      form: {
        // 表单绑定数据
        keyword: '',
        state: ''
      },
      query: {
        // 页码数据
        page: 1,
        pagesize: 10
      },
      tableData: [
        {
          username: '',
          title: '',
          createTime: '',
          articleBody: '',
          creatorID: '',
          id: '',
          state: '',
          videoURL: null,
          visits: ''
        }
      ],
      counts: 0, // 数据总数
      addDialogVisible: false, // 修改/新增弹框
      previewDialogVisible: false, // 预览弹框
      ArticleId: '', // 点击修改的id
      isEdit: false, // 判断是编辑还是修改
      ArticlesPreviewOBj: '', // 预览对象
      videoDialogVisible: false, // 视频是否显示
      videoState: false, // 视频状态判断
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: true, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: 'video/mp4', // 类型
            // url地址
            src: ''
            // src: 'https://media.w3.org/2010/05/sintel/trailer.mp4'
          }
        ],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }

      }

    }
  },
  created() {
    this.getArticleList()
  },
  methods: {
    // 获取文章列表
    async getArticleList() {
      const res = await list(this.query)
      console.log(res)
      this.tableData = res.data.items
      this.counts = res.data.counts
    },

    // 枚举数据方法
    stateFn(state) {
      if (state !== '') {
        // console.log(id)
        const obj = this.stateObj.filter((item) => item.id === state)
        return `已${obj[0].name}`
      }
    },

    // 点击搜索
    onSubmit() {
      if (this.form.keyword !== '' || this.form.state !== '') {
        this.query.page = 1
        if (this.form.state === '') {
          this.query.keyword = this.form.keyword
        } else {
          this.query = { ...this.query, ...this.form }
        }

        this.getArticleList()
      } else {
        this.query = {
          page: 1,
          pagesize: 10
        }
        this.getArticleList()
      }
    },

    // 点击清除
    delFormValue() {
      this.form = {
        keyword: '',
        state: ''
      }
      this.query = {
        page: 1,
        pagesize: 10
      }
      this.$refs.form.resetFields()
    },

    // 点击播放视频
    videoFn(url) {
      this.videoDialogVisible = true
      this.playerOptions.sources[0].src = url
    },

    // 点击关闭视频
    videoDelFn() {
      this.videoDialogVisible = false
      this.videoState = false
    },

    // 视频播放事件   视频从地址加载触发  如果视频不加载则不触发
    onPlayerLoadeddata() {
      this.videoState = true
    },

    // 预览
    perciewArticle(ArticleObj) {
      this.ArticlesPreviewOBj = ArticleObj
      this.previewDialogVisible = true
    },

    // 启用禁用方法
    async setStartFn(newstate, id) {
      const state = newstate === 0 ? 1 : 0
      const res = await changeState({ state, id })
      // console.log(res)
      this.$message.success(res.data.success === true && state === 0 ? '已禁用' : '已启用')
      this.getArticleList()
    },

    // 修改按钮
    editArticleFn(id) {
      console.log(id)
      this.isEdit = true
      this.addDialogVisible = true
      this.ArticleId = id
    },

    // 点击删除
    async removeArticleFn(data) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmRes === 'cancel') return
      const res = await remove(data)
      // console.log(res)
      this.$message.success(
        res.data.success === true ? '删除成功' : '删除失败'

      )
      if (this.tableData.length === 1) {
        this.query.page--
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      this.getArticleList()
    },

    // 新增技巧
    setArticleFn() {
      this.isEdit = false
      this.addDialogVisible = true
    },

    // 添加/修改/成功回调
    addClose() {
      if (this.form.keyword !== '' || this.form.state !== '') {
        this.query.page = 1
        if (this.form.state === '') {
          this.query.keyword = this.form.keyword
        } else {
          this.query = { ...this.query, ...this.form }
        }
      } else {
        this.query = {
          page: 1,
          pagesize: 10
        }
      }
      this.$refs.addArticle.clearDataFn()
      this.addDialogVisible = false
      this.getArticleList()
    },

    // 新增/修改取消按钮回调
    closeCancel() {
      this.$refs.addArticle.clearDataFn()
      this.addDialogVisible = false
    },

    // 新增修改弹框关闭回调
    closeFn() {
      this.$refs.addArticle.clearDataFn()
    },

    // 每页几条改变
    handleSizeChange(val) {
      this.query.pagesize = val
      this.getArticleList()
    },

    // 改变页数
    handleCurrentChange(val) {
      this.query.page = val
      this.getArticleList()
    }
  }
}
</script>

<style scoped lang='less'>
.formfixe {
  display: flex;

}
.el-input__innerr {
  width: 200px !important;
  height: 30px !important;
}
.formItem {
  margin-top: -2px !important;
}

.el-col {
  border-radius: 4px;
}

.bg-purple {
  background: #f4f4f5;
  line-height: 36px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.el-icon-info {
  margin: 0 10px;
  color: #909399;
}
.span-font {
  font-size: 13px;
  color: #909399;
}
.app-container {
  padding: 10px !important;
}
.video-style{
  position: fixed;
  top: 200px;
  left: 50%;
  width: 800px;
  height: 600px;
  margin-left: -400px;
  line-height: 600px;

}

.close-video{
  position: fixed;
  top: 100px;
  left: 50%;
  margin-left: -25px;

  width: 50px;
  height: 50px;
  padding: 10px;
  border-radius: 50%;
  background-color: #000;
  opacity: 0.5;
}
.i-font{
  font-size: 30px;
}
.dialog-displacement{
  margin-left: -999999px;
}
.el-pagination{
  text-align: right;
}
</style>
